import {
	baseUrl
} from './env';
import { getToken } from 'src/util/auth';
import axios from 'axios';
import { Message } from 'element-ui';
import { setStore, getStore } from 'src/config/mUtils'

export default async ({ url = '', data = {}, method = 'fetch', isLogin = false }) => {
	if (!url.match('http')) {
		url = baseUrl + url;
	}

	var http = axios.create({
		baseURL: baseUrl
	});

	return new Promise((resolve, reject) => {
		if (isLogin) {
			// 登录、注册
			http({
				method: method,
				url: url,
				data: data,
				params: (method == 'get' || method == 'GET') ? data : null,
				headers: {
					"Content-Type": 'application/json;charset=utf-8'
				},
				withCredentials: true,
			}).then((response) => {
				if (response.data.status > 200) {
					Message.error(response.data.message);
					resolve(response.data);
					return
				}

				if (response.data.status === 200) {
					resolve(response.data.data);
				}
			})
		} else {
			var token = JSON.parse(getStore('userInfo')) && JSON.parse(getStore('userInfo')).token;

			http({
				method: method,
				url: url,
				data: data,
				params: (method == 'get' || method == 'GET') ? data : null,
				headers: {
					"Authorization": token || 'no_value',
					"Content-Type": 'application/json;charset=utf-8'
				},
				withCredentials: false,
			}).then((res) => {
				res = res.data;
				if (res.status === 401) {
					setStore('userInfo', {});
					// token过期
					let hash = window.location.hash && window.location.hash.split('#')[1];

					let origin = window.location.href && window.location.href.split('#')[0];
					hash = hash.split('=')[1] || hash;
					// 保留预存路由
					// window.location.href = origin + '#/login?redirect=' + hash;
					window.location.href = origin + '#/login';
					Message.error('token失效，请重新登录');
					window.close();
					return;
				}

				if (res.status > 200) {
					Message.error(res.message);
					return;
				}
				if (res.status === 200) {
					resolve(res.data);
				}
			})
		}
	})
}
